#!/usr/bin/env python
"""
简单测试GitCode MCP服务器是否能正确启动
"""
import subprocess
import time
import os
import signal
import sys

def main():
    """启动服务器并检查是否正常运行"""
    print("开始测试GitCode MCP服务器...\n")
    
    # 设置环境变量
    env = os.environ.copy()
    if not env.get("GITCODE_TOKEN"):
        print("⚠️ 警告: 未设置GITCODE_TOKEN环境变量")
        print("某些功能可能无法正常工作")
        
    # 启动服务器
    cmd = ["python", "-m", "gitcode_mcp.server"]
    print(f"启动命令: {' '.join(cmd)}")
    
    process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        env=env,
        text=True,
        bufsize=1
    )
    
    print("服务器进程已启动，进程ID:", process.pid)
    print("正在等待服务器初始化...\n")
    
    # 监控服务器输出
    start_time = time.time()
    success = False
    error_found = False
    lines_captured = []
    
    try:
        # 最多等待10秒
        while time.time() - start_time < 10:
            if process.poll() is not None:
                # 进程已结束
                print("❌ 服务器意外退出")
                break
            
            line = process.stdout.readline().strip()
            if line:
                lines_captured.append(line)
                print(f"服务器输出: {line}")
                
                # 检查是否有成功启动的迹象
                if "GitCode MCP服务器已初始化" in line:
                    success = True
                    break
                # 检查错误
                elif "error" in line.lower() or "exception" in line.lower():
                    error_found = True
            
            time.sleep(0.1)
        
        # 检查结果
        if success:
            print("\n✅ 服务器启动成功!")
            print("服务器接受请求中...")
            
            # 等待5秒，让服务器稳定运行
            time.sleep(5)
            
            print("\n📝 测试总结:")
            print("- 服务器能够正常启动")
            print("- GitCode MCP功能就绪")
            print("- 服务器进程保持稳定运行")
            
            print("\n🎉 测试通过! GitCode MCP服务器可以正常使用")
        elif error_found:
            print("\n❌ 服务器启动过程中出现错误")
        else:
            print("\n⚠️ 未能确认服务器是否成功启动")
            
    except KeyboardInterrupt:
        print("\n接收到中断信号")
    finally:
        # 清理进程
        if process and process.poll() is None:
            print("\n正在终止服务器进程...")
            try:
                process.terminate()
                process.wait(timeout=3)
            except subprocess.TimeoutExpired:
                print("进程未响应，强制终止...")
                process.kill()
        
        print("\n测试完成")

if __name__ == "__main__":
    main() 